//
//  Response.swift
//  
//
//  Created by tank on 2021/10/18.
//

import Foundation
import Moya

public extension Response {
    func map<T: Codable>() throws -> APIResult<T> {
        do {
            return try JSONDecoder().decode(APIResult<T>.self, from: data)
        } catch {
            HttpService.shared.logger.error(.init(stringLiteral: error.localizedDescription))
            throw MoyaError.objectMapping(error, self)
        }
    }
    
    func map<T>() throws -> APIResult<T> {
        guard let jsonDictionary = try mapJSON() as? Dictionary<String, Any> else {
            HttpService.shared.logger.error(.init(stringLiteral: APIResultError.appResultMapping.localizedDescription))
            throw MoyaError.objectMapping(APIResultError.appResultMapping, self)
        }
        
        guard let code = jsonDictionary["code"] as? Int else {
            HttpService.shared.logger.error(.init(stringLiteral: APIResultError.notFindCodeKey.localizedDescription))
            throw MoyaError.objectMapping(APIResultError.notFindCodeKey, self)
        }
        
        let message = jsonDictionary["message"] as? String
        
        let data = jsonDictionary["data"] as? T
        
        return APIResult<T>(code: code, message: message, data: data)
    }
}
